<?php
namespace common\components\services\message;
use common\components\helpers\EventData;
use common\components\helpers\Fun;
use common\components\helpers\Util;
use yii\base\Component;
use common\models\datas\MessageConfigItem;
use common\models\datas\MessageLog;
use yii\helpers\ArrayHelper;

class MessageEventManage  extends Component{

    public $eventArray;

    public $ownerArray;

    public $eventKey;

    private $_time_filed=['create_at','created_at','updated_at','update_at'];
    public function sendTelephoneValidateCode(){
        $config=$this->getConfig();
        if($this->eventKey>0&&$config!==null){
            $MessageTemplatesms=$this->getMessageTemplateSms($config);
            $messageway=serialize(['3'=>'sms']);
            $messagetype=$this->getMessageType();
            $sendgroup=$this->getSendGroup();
            $receive_array=$this->getReceiveArray($sendgroup);
            $id=$this->writeLog($messageway,$messagetype,'','','',$MessageTemplatesms,$sendgroup,$receive_array);
            /*\Yii::error('messageeventmanage sendtelephonevalidate code id:');
            \Yii::error($id);*/
            $object=\Yii::createObject(['class'=>MessageManage::className()]);
            $object->send($id,true,1);
        }
    }
    public function afterInsertSend(){
        $config=$this->getConfig();
        $message='';
        if($this->eventKey>0&&$config!==null){
            $MessageTemplatesys=$this->getMessageTemplatesSys($config);
            $MessageTemplatewechat=$this->getMessageTemplateWechat($config);
            $MessageTemplatemail=$this->getMessageTemplateMail($config);
            $MessageTemplatesms=$this->getMessageTemplateSms($config);
            $messageway=$this->getMessageWay($config);
            $messagetype=$this->getMessageType();
            $sendgroup=$this->getSendGroup();
            $receive_array=$this->getReceiveArray($sendgroup);
            $id=$this->writeLog($messageway,$messagetype,$MessageTemplatesys,$MessageTemplatewechat,$MessageTemplatemail,$MessageTemplatesms,$sendgroup,$receive_array);
            $object=\Yii::createObject(['class'=>MessageManage::className()]);
            $object->send($id,true,1);
        }
        return $message;
    }
    private function getConfig(){
        return MessageConfigItem::find()->where(['site_id'=>Fun::getSiteId()])->joinWith(['messageConfig' => function ($query) {
            $query->andWhere(['event_id' => $this->eventKey]);
        }])->asArray()->one();
    }
    private function getSendGroup(){
        $config=MessageConfigItem::find()->where(['site_id'=>Fun::getSiteId()])->joinWith(['messageConfig' => function ($query) {
        $query->andWhere(['event_id' => $this->eventKey]);
        }])->one();
        return (!empty($config) && isset($config->messageConfig))?$config->messageConfig->send_group:'';
    }
    private function getMessageWay($config){
        return $config['send_way'];
    }
    private function getMessageType(){
      $type=$this->getConfig()['messageConfig']['type_id'];
        return $type;
    }
    private function getMessageTemplatesSys($config){
        $messageway=unserialize($this->getMessageWay($config));
        //\Yii::error($this->ownerArray);
        $str_sys='';
        if(in_array('sys',$messageway)){
            $str_sys=$config['template_sys'];
            foreach($this->ownerArray as $k=>$v){
                if(strpos($str_sys,'{$'.$k.'}')) {
                    $str_sys = str_replace('{$' . $k . '}', $v, $str_sys);
                }
            }
        }
//        $str_sys=preg_replace("/\s+/", "", $str_sys); //匹配任何空白字符，包括空格、制表符、换页符等。与 [ \f\n\r\t\v] 等效
        return $str_sys;
    }

    private function getMessageTemplateWechat($config){
        $messageway=unserialize($this->getMessageWay($config));
        $str_wechat='';
        if(in_array('wechat',$messageway)){
            $str_wechat=$config['template_wechat'];
            foreach($this->ownerArray as $k=>$v){
                if(strpos($str_wechat,'{$'.$k.'}'))
                $str_wechat=str_replace('{$'.$k.'}',$v,$str_wechat);
            }
        }
//        $str_wechat=preg_replace("/\s+/", "", $str_wechat); //匹配任何空白字符，包括空格、制表符、换页符等。与 [ \f\n\r\t\v] 等效
        return $str_wechat;
    }
    private function getMessageTemplateMail($config){
        $messageway=unserialize($this->getMessageWay($config));
        $str_mail='';
        if(in_array('email',$messageway)){
            $str_mail=$config['template_mail'];
            foreach($this->ownerArray as $k=>$v){
                if(strpos($str_mail,'{$'.$k.'}'))
                $str_mail=str_replace('{$'.$k.'}',$v,$str_mail);
            }
        }
//        $str_mail=preg_replace("/\s+/", "", $str_mail); //匹配任何空白字符，包括空格、制表符、换页符等。与 [ \f\n\r\t\v] 等效
        return $str_mail;
    }
    private function getMessageTemplateSms($config){
        $messageway=unserialize($this->getMessageWay($config));
        $str_sms='';
        if(in_array('sms',$messageway)){
            $str_sms=$config['template_sms'];
            foreach($this->ownerArray as $k=>$v){
                if(strpos($str_sms,'{$'.$k.'}'))
                $str_sms=str_replace('{$'.$k.'}',$v,$str_sms);
            }
        }
//        $str_sms=preg_replace("/\s+/", "", $str_sms); //匹配任何空白字符，包括空格、制表符、换页符等。与 [ \f\n\r\t\v] 等效
        return $str_sms;
    }
    private function getReceiveArray($sendgroup){
        $send_group_array=(new EventData())->getSendGroupArrayByKey($sendgroup);
        if($send_group_array!=null ){
            $key=$send_group_array['key'];
            return $receiver_arr=ArrayHelper::keyExists($key,$this->ownerArray)?(is_array($this->ownerArray[$key])?serialize($this->ownerArray[$key]):serialize([$this->ownerArray[$key]])):'';
        }
        return '';
    }
    private function writeLog($way,$type,$templatesys,$templatewechat,$templatemail,$templatesms,$sendgroup,$receive_array){
        $MessageLog=new MessageLog();
        $MessageLog->content_sys=$templatesys;
        $MessageLog->content_wechat=$templatewechat;
        $MessageLog->content_mail=$templatemail;
        $MessageLog->content_sms=$templatesms;
        $MessageLog->send_way=$way;
        $MessageLog->site_id=Fun::getSiteId();
        $MessageLog->type_id=$type;
        $MessageLog->send_group=$sendgroup;
        $MessageLog->receiver_arr=$receive_array;
        $MessageLog->admin_id=1;
        if($MessageLog->save(false)){return $MessageLog->id;}
    }
}